#include "input.h"
#include "ltgsql.h"
#include <stdio.h>
#include <stdlib.h>
#include <string.h>

#ifdef LTGSQL_WINDOWS
#include <windows.h>
#include <io.h>
#include <conio.h>

#define MAX_HISTORY_SIZE 100
#define MAX_LINE_LENGTH 1024

static char* history[MAX_HISTORY_SIZE];
static int history_count = 0;
static int history_index = 0;

// Windows 控制台颜色设置
void set_console_color(int color) {
    HANDLE hConsole = GetStdHandle(STD_OUTPUT_HANDLE);
    SetConsoleTextAttribute(hConsole, color);
}

// 获取终端宽度
int get_console_width() {
    CONSOLE_SCREEN_BUFFER_INFO csbi;
    GetConsoleScreenBufferInfo(GetStdHandle(STD_OUTPUT_HANDLE), &csbi);
    return csbi.srWindow.Right - csbi.srWindow.Left + 1;
}

// Windows 版本的 readline
char* ltgsql_readline(const char* prompt) {
    printf("%s", prompt);
    fflush(stdout);

    char* buffer = ltgsql_malloc(MAX_LINE_LENGTH);
    if (!buffer) {
        return NULL;
    }

    int pos = 0;
    int ch;

    while (1) {
        ch = _getch();

        if (ch == '\r' || ch == '\n') {
            // 回车键
            printf("\n");
            buffer[pos] = '\0';
            break;
        }
        else if (ch == 8 || ch == 127) {
            // 退格键
            if (pos > 0) {
                pos--;
                printf("\b \b"); // 回退并擦除
            }
        }
        else if (ch == 3) {
            // Ctrl+C
            printf("^C\n");
            ltgsql_free(buffer);
            return NULL;
        }
        else if (ch == 0xE0) {
            // 方向键等特殊键
            ch = _getch();
            // 这里可以添加方向键处理（历史记录浏览）
        }
        else if (ch >= 32 && ch <= 126) {
            // 可打印字符
            if (pos < MAX_LINE_LENGTH - 1) {
                buffer[pos++] = ch;
                printf("%c", ch);
            }
        }
    }

    return buffer;
}

void ltgsql_add_history(const char* line) {
    if (history_count < MAX_HISTORY_SIZE) {
        history[history_count++] = ltgsql_strdup(line);
    } else {
        // 移除最旧的历史记录
        ltgsql_free(history[0]);
        for (int i = 1; i < MAX_HISTORY_SIZE; i++) {
            history[i - 1] = history[i];
        }
        history[MAX_HISTORY_SIZE - 1] = ltgsql_strdup(line);
    }
    history_index = history_count;
}

void ltgsql_save_history(const char* filename) {
    FILE* fp = fopen(filename, "w");
    if (fp) {
        for (int i = 0; i < history_count; i++) {
            fprintf(fp, "%s\n", history[i]);
        }
        fclose(fp);
    }
}

void ltgsql_load_history(const char* filename) {
    FILE* fp = fopen(filename, "r");
    if (fp) {
        char line[MAX_LINE_LENGTH];
        while (fgets(line, sizeof(line), fp)) {
            // 去除换行符
            line[strcspn(line, "\r\n")] = '\0';
            if (strlen(line) > 0) {
                ltgsql_add_history(line);
            }
        }
        fclose(fp);
    }
}

#endif // LTGSQL_WINDOWS